﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Security.Cryptography;
using System.Web;
using CNVP.Config;
using CNVP.Framework.Utils;

namespace CNVP.Framework
{
    public class License
    {
        #region 字符可逆加密
        string iv = "YesWeCan.";
        string key = "Best2010";

        /// <summary>
        /// DES加密偏移量，必须是>=8位长的字符串
        /// </summary>
        public string IV
        {
            get { return iv; }
            set { iv = value; }
        }

        /// <summary>
        /// DES加密的私钥，必须是8位长的字符串
        /// </summary>
        public string Key
        {
            get { return key; }
            set { key = value; }
        }

        #region 字符串加密解密
        /// <summary>
        /// 对字符串进行DES加密
        /// </summary>
        /// <param name="sourceString">待加密的字符串</param>
        /// <returns>加密后的BASE64编码的字符串</returns>
        public string Encrypt(string sourceString)
        {
            byte[] btKey = Encoding.Default.GetBytes(key);
            byte[] btIV = Encoding.Default.GetBytes(iv);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Encoding.Default.GetBytes(sourceString);
                try
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);
                        cs.FlushFinalBlock();
                    }

                    return Convert.ToBase64String(ms.ToArray());
                }
                catch
                {
                    throw;
                }
            }
        }

        /// <summary>
        /// 对DES加密后的字符串进行解密
        /// </summary>
        /// <param name="encryptedString">待解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public string Decrypt(string encryptedString)
        {
            byte[] btKey = Encoding.Default.GetBytes(key);
            byte[] btIV = Encoding.Default.GetBytes(iv);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Convert.FromBase64String(encryptedString);
                try
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);
                        cs.FlushFinalBlock();
                    }

                    return Encoding.Default.GetString(ms.ToArray());
                }
                catch
                {
                    throw;
                }
            }
        }
        #endregion
        #region 文件加密解密
        /// <summary>
        /// 对文件内容进行DES加密
        /// </summary>
        /// <param name="sourceFile">待加密的文件绝对路径</param>
        /// <param name="destFile">加密后的文件保存的绝对路径</param>
        public void EncryptFile(string sourceFile, string destFile)
        {
            if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在！", sourceFile);

            byte[] btKey = Encoding.Default.GetBytes(key);
            byte[] btIV = Encoding.Default.GetBytes(iv);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] btFile = File.ReadAllBytes(sourceFile);

            using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
            {
                try
                {
                    using (CryptoStream cs = new CryptoStream(fs, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(btFile, 0, btFile.Length);
                        cs.FlushFinalBlock();
                    }
                }
                catch
                {
                    throw;
                }
                finally
                {
                    fs.Close();
                }
            }
        }

        /// <summary>
        /// 对文件内容进行DES加密，加密后覆盖掉原来的文件
        /// </summary>
        /// <param name="sourceFile">待加密的文件的绝对路径</param>
        public void EncryptFile(string sourceFile)
        {
            EncryptFile(sourceFile, sourceFile);
        }

        /// <summary>
        /// 对文件内容进行DES解密
        /// </summary>
        /// <param name="sourceFile">待解密的文件绝对路径</param>
        /// <param name="destFile">解密后的文件保存的绝对路径</param>
        public void DecryptFile(string sourceFile, string destFile)
        {
            if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在！", sourceFile);

            byte[] btKey = Encoding.Default.GetBytes(key);
            byte[] btIV = Encoding.Default.GetBytes(iv);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] btFile = File.ReadAllBytes(sourceFile);

            using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
            {
                try
                {
                    using (CryptoStream cs = new CryptoStream(fs, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(btFile, 0, btFile.Length);
                        cs.FlushFinalBlock();
                    }
                }
                catch
                {
                    throw;
                }
                finally
                {
                    fs.Close();
                }
            }
        }

        /// <summary>
        /// 对文件内容进行DES解密，加密后覆盖掉原来的文件
        /// </summary>
        /// <param name="sourceFile">待解密的文件的绝对路径</param>
        public void DecryptFile(string sourceFile)
        {
            DecryptFile(sourceFile, sourceFile);
        }
        #endregion
        #endregion
        #region 授权码操作(最多允许43个汉字或者字符)
        /// <summary>
        /// 生成RSA密钥对
        /// </summary>
        //public static void CreateRSAKey()
        //{
        //    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        //    RSAParameters keys = rsa.ExportParameters(true);
        //    string pkxml = "<root>\n<Modulus>" + Convert.ToBase64String(keys.Modulus) + "</Modulus>";
        //    pkxml += "\n<Exponent>" + Convert.ToBase64String(keys.Exponent) + "</Exponent>\n</root>";

        //    string psxml = "<root>\n<Modulus>" + Convert.ToBase64String(keys.Modulus) + "</Modulus>";
        //    psxml += "\n<Exponent>" + Convert.ToBase64String(keys.Exponent) + "</Exponent>";
        //    psxml += "\n<D>" + Convert.ToBase64String(keys.D) + "</D>";
        //    psxml += "\n<DP>" + Convert.ToBase64String(keys.DP) + "</DP>";
        //    psxml += "\n<P>" + Convert.ToBase64String(keys.P) + "</P>";
        //    psxml += "\n<Q>" + Convert.ToBase64String(keys.Q) + "</Q>";
        //    psxml += "\n<DQ>" + Convert.ToBase64String(keys.DQ) + "</DQ>";
        //    psxml += "\n<InverseQ>" + Convert.ToBase64String(keys.InverseQ) + "</InverseQ>\n</root>";

        //    Utils.FileUtils.SaveFile(pkxml, HttpContext.Current.Server.MapPath("~/Config/PublicKey.xml"));
        //    Utils.FileUtils.SaveFile(psxml, HttpContext.Current.Server.MapPath("~/Config/PrivateKey.xml"));
        //}
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        //public static string EncodeRSA(string Str)
        //{
        //    try
        //    {
        //        Utils.RSAUtils rsahd = new Utils.RSAUtils();
        //        //RSACryptoServiceProvider rsaprd1 = rsahd.CreateRSAEncryptProvider(HttpContext.Current.Server.MapPath("~/Config/PublicKey.xml"));
        //        RSACryptoServiceProvider rsaprd1 = rsahd.CreateRSAEncryptProvider();
        //        byte[] data = new UnicodeEncoding().GetBytes(Str);
        //        byte[] endata = rsaprd1.Encrypt(data, true);
        //        return Convert.ToBase64String(endata);
        //    }
        //    catch (Exception ex)
        //    {
        //        return ex.ToString();
        //    }
        //}
        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string DecodeRSA(string Str)
        {
            try
            {
                Utils.RSAUtils rsahd = new Utils.RSAUtils();
                RSACryptoServiceProvider rsaprd = rsahd.CreateRSAProvider();
                byte[] data = Convert.FromBase64String(Str);
                byte[] dedata = rsaprd.Decrypt(data, true);
                return (new UnicodeEncoding()).GetString(dedata);
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
        #endregion
        #region 匹配序列号值
        public static String ActivationCode { get { try { return EncryptUtils.DecodeCookies(LicenseConfig.activationCode); } catch { return String.Empty; } } }
        /// <summary>
        /// 域名授权
        /// </summary>
        /// <returns></returns>
        public static bool AllowHost()
        {
            bool flg = false;
            string _Host = Utils.Public.GetHost();
            string[] _HostAry = _Host.Split('.');
            if (Regex.IsMatch(_HostAry[0], @"^127|192|localhost",RegexOptions.IgnoreCase))
            {
                flg = true;
            }
            else
            {
                if (!String.IsNullOrEmpty(ActivationCode))
                {
                    string Domains = Config.ActivationCode.GetConfigValue(ActivationCode, "Domain");
                    Domains = Domains.ToLower();
                    string[] _Domains = Domains.Split(',');
                    for (int i = 0; i < _Domains.Length; i++)
                    {
                        if (_Domains[i] == _Host)
                        {
                            flg = true;
                            break;
                        }
                    }
                }
            }
            return flg;
        }
        /// <summary>
        /// 到期判断(True已经到期|Flase还未到期)
        /// </summary>
        /// <returns></returns>
        public static bool ISExpire()
        {
            if (!String.IsNullOrEmpty(ActivationCode))
            {
                string _DateTime = Config.ActivationCode.GetConfigValue(ActivationCode, "EndDate");
                int Year = Convert.ToDateTime(_DateTime).Year;
                int Month = Convert.ToDateTime(_DateTime).Month;
                int Day = Convert.ToDateTime(_DateTime).Day;
                DateTime ExpireTime = new DateTime(Year, Month, Day);
                DateTime NowTime = Convert.ToDateTime(DateTime.Now.ToString());
                return (ExpireTime <= NowTime);
            }
            else
            {
                return false;
            }
        }
        #endregion
    }
}